package Classic150;

import Tree.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class 二叉树的层平均值 {

    List<Double> sums = new ArrayList<>();
    List<Integer> counts = new ArrayList<>();
    List<Double> averages = new ArrayList<>();

    public List<Double> averageOfLevels(TreeNode root) {
        /*
            递归
         */
        averageOfLevelsRecursion(root, 0);
        for (int i = 0; i < sums.size(); i++) averages.add(sums.get(i) / counts.get(i));
        return averages;

        /*
            迭代
         */
        /*List<Double> res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            double sum = 0;
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                sum += node.val;
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
            res.add(sum / size);
        }
        return res;*/
    }

    private void averageOfLevelsRecursion(TreeNode node, int deep) {
        if (node == null) return;
        if (sums.size() == deep) {
            sums.add((double) node.val);
            counts.add(1);
        } else {
            sums.set(deep, sums.get(deep) + node.val);
            counts.set(deep, counts.get(deep) + 1);
        }
        averageOfLevelsRecursion(node.left, deep + 1);
        averageOfLevelsRecursion(node.right, deep + 1);
    }
}
